#include "lsmtree.h"
#include "mem.h"
#include "disk.h"

namespace VirtualR {
bool LSMTree::file_open(std::string file_dir) {
  disk_ = new (std::nothrow) Disk(file_dir);
  if (disk_ == nullptr) {
    std::cout << "new disk error. out of memory" << std::endl;
    return false;
  }

  return true;
}

bool LSMTree::get(std::string key, std::string &value) {
  std::pair<bool, std::string> res;
  if (mem_->get(key, value)) { // memeory find
    return true;
  } else { // disk find
    res = disk_->search(key);
  }

  value = res.second;
  if (res.first == false) {
    fail_count_++;
    return false;
  }
  success_count_++;
  return true;
}

bool LSMTree::put(std::string key, std::string value) {
  bool flag = false;
  if (mem_ == nullptr) {
    mem_ = new (std::nothrow) SkipList();
    if (mem_ == nullptr) {
      std::cout << "new mem error" << std::endl;
      assert(false);
    }
  }
  flag = mem_->put(key, value);
  if (mem_->space() >= MEM_MAX_SIZE) {
    disk_->add(*mem_);
    delete mem_;
    mem_ = nullptr;
  }
  return flag;
}

bool LSMTree::del(std::string key) {
  std::pair<bool, std::string> res;
  res.first = mem_->del(key);
  if (res.first) {
    return res.first;
  }

  res = disk_->search(key);
  if (res.first == false || res.second == "") {
    return true;
  }
  res.first = mem_->put(key, "");
  return res.first;
}

} // namespace VirtualR